package com.atguigu.day12;

import com.atguigu.bean.WaterSensor;
import com.atguigu.bean.WaterSensor1;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.e;

public class Flink03_SQL_RegisterTable {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.获取表的环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 3.想将Table注册为带表名的表

        //从端口读取数据
        SingleOutputStreamOperator<WaterSensor1> streamSource = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor1>() {
                    @Override
                    public WaterSensor1 map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor1(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //将流转为表
//        Schema.newBuilder()
//                .column("id",)
//                .build();
//        tableEnv.fromDataStream(streamSource,$("id"),$("ts"),$("vc"));
        Table table = tableEnv.fromDataStream(streamSource);

        //将Table对象注册为虚表（带表名）
        tableEnv.createTemporaryView("sensor",table);

        //使用sql的方式查询虚表的数据
//        tableEnv.executeSql("select * from sensor").print();
        //使用sql的方式查询Table对象的数据
        tableEnv.executeSql("select * from "+table).print();

        env.execute();
    }
}
